<template>
	<view class="swiperTab-box bb">
		<scroll-view class="scroll-view" :scrollLeft="scrollLeft" scrollX scrollWithAnimation>
			<view class="flex col-center pos-r">
				<view class="detail pl-30 pr-30 flex flex-nowrap" v-for="(obj,index) in data" :key="index"
					@tap="getTabRect(1,index)">
					{{obj}}
				</view>
				<view class="tabs-line" :style="{ left: barLeft+'px', width: barWidth+'rpx' }" />
			</view>
		</scroll-view>

	</view>
</template>

<script>
	export default {
		props: {
			data: {
				type: Array,
				default () {
					return [{
						name: '全部',
						code: ''
					}]
				}
			}, //tab 列表
			barWidth: {
				type: Number,
				default: 60
			}, //下划线长度
			tabIndex: {
				type: [String, Number],
				default () {
					return 0
				}
			}, //默认选中
		},
		data() {
			return {
				scrollLeft: 0, //滚动条位置  :scrollLeft="scrollLeft"
				barLeft: 0, //提示位置
				index: 0, //选中位置
			}
		},
		methods: {

			//选中位置
			getTabRect(isTap, index) {
				this.index = index;
				const query = uni.createSelectorQuery().in(this);
				var offsetLeft = 0; //距父级左边的距离
				query.selectAll(".detail").boundingClientRect((res) => {
					for (var i = 0; i < index; i++) {
						offsetLeft += res[i].width;
					}
					this.barLeft = offsetLeft + (res[index].width - uni.upx2px(this.barWidth)) / 2; //计算提示位置
					this.countScroll(offsetLeft, res[index].width); //计算滚动条位置
					this.$emit('input', index)
					this.$emit('change', this.data[index], isTap) // isTap 0初始化 1第一次加载
				}).exec();

			},
			//计算滚动条位置
			countScroll(offsetLeft, width) {
				//console.log("offsetLeft",offsetLeft,"width",width)
				const query = uni.createSelectorQuery().in(this);
				query.select(".scroll-view").fields({
					rect: true,
					size: true,
					scrollOffset: true
				}, data => {
					var offL = offsetLeft + width / 2; //内容中心距离距 父级左边的距离
					var showW = data.width / 2; //父级中心位置
					this.scrollLeft = (offL < showW) ? 0 : offL - showW;
				}).exec();
			},
		},
		mounted() {

			this.getTabRect(0, this.tabIndex);
		},

	}
</script>

<style lang="scss" scoped>
	//公共样式  作为插件的时候需要
	.bb {
		border-bottom: 1px solid #eee;
	}

	.flex {
		display: flex;
	}

	.col-center {
		align-items: center;
	}

	//垂直 列  居中
	.pos-r {
		position: relative !important;
	}

	.flex-nowrap {
		flex-wrap: nowrap;
	}

	// 默认值  不拆行或不拆列 --

	.pr-30 {
		padding-right: 30rpx !important;
	}

	.pl-30 {
		padding-left: 30rpx !important;
	}

	//公共样式  作为插件的时候需要    end
	.swiperTab-box {
		position: sticky;
		top: 0;
		height: 72rpx;
		line-height: 72rpx;
		background-color: #fff;

		.flex {
			white-space: nowrap;
		}

		.tabs-line {
			position: absolute;
			bottom: 3rpx;
			height: 4rpx;
			border-radius: 3rpx;
			background-color: #50CC94;
			transition: left .3s, width .3s;
		}
	}
</style>
